<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>我是页面1</h1>
  <script>
    document.addEventListener('visibilitychange', function() {
      console.log(document.visibilityState);
      if (document.visibilityState === 'hidden'){
        document.title = '别看tab2了，看我';
      } else if (document.visibilityState === "visible") {
        document.title = 'tab1';
      }
    })

    let n = 0;
    let isFirst = true; 

    window.onfocus = function() {
      if(!isFirst) {
        alert(`请注意，你切屏了！总共离开${n}秒`);
        isFirst = true
        n = 0
      }
      document.title = 'tab1';
    }

    window.onblur = function() {
      // alert('请注意，你切屏了！');
      isFirst = false
      setInterval(() => {
        n++
      }, 1000)
    }

  </script>
</body>
</html>